package com.itheima.Demo02_事务;

import com.itheima.jdbcUtils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class demo01 { // 设置事务为手动提交
    @Test
    public void Test01(){
        //使用工具包 获取 连接对象
        Connection connection = null;
        Statement statement=null;
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();
            //设置事务为手动提交
            connection.setAutoCommit(false);
            //模拟转账
            int i = statement.executeUpdate(" UPDATE account set money=money-100 where name='a' ");
            if (i>0){
                connection.commit();//提交事务
                System.out.println("转账成功！");
            }
            int i1 = statement.executeUpdate(" UPDATE account set money=money+100 where name='b'");
            if (i1>0){
                connection.commit();//提交事务
                System.out.println("收款成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //如果出现异常则回滚
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {//必须执行
            //调用工具包 释放资源
            JDBCUtils.Close(connection,statement,null);
        }

    }
}
